from django.core.paginator import Paginator
from rest_framework.response import Response
from rest_framework.views import APIView
from .sers import *


# 开发 广告接口
class IndexView(APIView):
    def get(self, request):
        # 查询轮播
        queryset_banner = AdvContent.objects.filter(category__key=1).order_by("sort")
        # 查询 快讯
        queryset_kuaixun = AdvContent.objects.filter(category__key=2).order_by("sort")
        # 查看 图片广告
        adv_pic = AdvContent.objects.filter(category__key=3).order_by("sort").first()

        #展示商品信息
        #查询所有的一级分类
        queryset = Category.objects.filter(parent_id=None)

        resp = {
            "banner_list": AdvSer(queryset_banner, many=True).data,
            "news_list": AdvSer(queryset_kuaixun, many=True).data,
            "adv_pic": AdvSer(adv_pic).data,
            "category_list": CategoryGoodsSer(queryset, many=True).data
        }

        return Response(resp)


# 专门开发一个 分类接口
class ChannelView(APIView):
    def get(self, request):
        #  查询所有的频道
        queryset_channel = Channel.objects.all()

        ser = ChannelSer(queryset_channel, many=True)

        return Response(ser.data)


class GoodsListView(APIView):
    #获取参数三级分类外键id，flag(用来区别不同排序方式)，num页数
    def get(self,request,cid,flag,num=1):
        if flag == 1:
            queryset = Goods.objects.filter(category3=cid)
        elif flag == 2:
            queryset = Goods.objects.filter(category3=cid).order_by('price')
        elif flag == 3:
            queryset = Goods.objects.filter(category3=cid).order_by("-sale")
        else:
            queryset = Goods.objects.filter(category3=cid)
        #一页两条记录
        size = 2
    #分页器实现分页效果
        #1.创建一个分页器对象
        p = Paginator(queryset,size)
        #2.根据页码获取一页数据
        page_queryset = p.get_page(num)

        resp = {
            'data':GoodsListSer(page_queryset,many=True).data,#获取单页数据
            'total':p.count,#总页数
            'size':size#一页大小
        }
        return Response(resp)